package com.ruoyi.qiushi.service.wechat.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.qiushi.domain.mall.TradeAfterSale;
import com.ruoyi.qiushi.domain.mall.TradeOrderItem;
import com.ruoyi.qiushi.domain.mall.TradeServiceOrder;
import com.ruoyi.qiushi.mapper.mall.TradeAfterSaleMapper;
import com.ruoyi.qiushi.mapper.mall.TradeOrderItemMapper;
import com.ruoyi.qiushi.mapper.mall.TradeOrderMapper;
import com.ruoyi.qiushi.mapper.mall.TradeServiceOrderMapper;
import com.ruoyi.qiushi.service.wechat.IPayService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 支付类
 */
@Service
public class PayServiceImpl implements IPayService {
    private static String ORDER_NOTIFY_URL = "/pay/orderWechatCallback";
    @Value("${pay.wechat.app_id}")
    private String appId;
    @Value("${pay.wechat.mchid}")
    private String mchid;
    @Value("${pay.wechat.base_url}")
    private String baseUrl;
    @Autowired(required = false)
    private JsapiServiceExtension jsapiServiceExtension;
    @Autowired(required = false)
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Autowired
    private TradeAfterSaleMapper tradeAfterSaleMapper;
    @Autowired
    private TradeOrderItemMapper tradeOrderItemMapper;
    @Autowired
    private TradeServiceOrderMapper tradeServiceOrderMapper;

    /**
     * 普通订单回调
     *
     * @param params
     * @param request
     */
    @Override
    public void orderWechatCallback(Map<String, Object> params, HttpServletRequest request) {
        RefundNotification transaction = this.analysisWechat(params, request);

        String refundNo = transaction.getOutRefundNo();
        TradeAfterSale tradeAfterSale = tradeAfterSaleMapper.selectTradeAfterSaleByRefundTradeNo(refundNo);

        tradeAfterSale.setStatus("2"); // 状态改为成功
        tradeAfterSale.setRefundTime(new Date());

        if (tradeAfterSale.getSpuType().equals("2")) {
            TradeOrderItem tradeOrderItem = tradeOrderItemMapper.selectTradeOrderItemById(tradeAfterSale.getOrderItemId());
            tradeOrderItem.setAfterSaleStatus("2");
            tradeOrderItem.setUpdateTime(new Date());

            tradeOrderItemMapper.updateTradeOrderItem(tradeOrderItem);
        } else if (tradeAfterSale.getSpuType().equals("3")) {
            TradeServiceOrder tradeServiceOrder = tradeServiceOrderMapper.selectTradeServiceOrderById(tradeAfterSale.getOrderId());
            tradeServiceOrder.setAfterSaleStatus("2");
            tradeServiceOrder.setUpdateTime(new Date());

            tradeServiceOrderMapper.updateTradeServiceOrder(tradeServiceOrder);
        }

        tradeAfterSale.setUpdateTime(new Date());
        tradeAfterSaleMapper.updateTradeAfterSale(tradeAfterSale);
    }

//    /**
//     * 服务订单支付回调
//     * @param params
//     * @param request
//     */
//    @Override
//    public void serviceOrderWechatCallback(Map<String,Object> params, HttpServletRequest request){
//        Transaction transaction = this.analysisWechat(params,request);
//        String orderNo = transaction.getOutTradeNo();
//        TradeServiceOrder order = serviceOrderService.getOrderByNo(orderNo);
//        order.setPayTradeNo(transaction.getTransactionId());
//        if(!TradeConstants.ORDER_STATUS_UNPAID.equals(order.getStatus())){
//            return ; //订单已处理
//        }
//        if(!"SUCCESS".equals(transaction.getTradeState().toString())) {
//            serviceOrderService.payFail(order);
//        }else{//支付成功
//            serviceOrderService.paySuccess(order);
//        }
//    }

    /**
     * 解析支付回调
     *
     * @param params
     * @param request
     * @return
     */
    private RefundNotification analysisWechat(Map<String, Object> params, HttpServletRequest request) {
        String body = JSONObject.toJSONString(params);
        String signature = request.getHeader("Wechatpay-Signature");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String serial = request.getHeader("Wechatpay-Serial");
        request.getHeader("Wechatpay-Signature-Type");

        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(body)
                .build();

        NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);
        RefundNotification refundNotification = parser.parse(requestParam, RefundNotification.class);
        return refundNotification;
    }
}
